<?php

include_once("dbconfig.php");
include_once("functions.php");

//jace 2011826
include_once '../admin/dataaccess/cs_parameter.php';
include_once '../admin/uploadFile/upload.php';
include_once("../admin/cfg/user.php");
include_once("../admin/dataaccess/event.php");

//include_once '../admin/dataaccess/common.php';

function addCalendar($st, $et, $sub, $ade) {
    $ret = array();
    try {
        $db = new DBConnection();
        $db->getConnection();
        $sql = "insert into `event` (`subject`, `start_time`, `end_time`, `is_allday_event`) values ('"
                . mysql_real_escape_string($sub) . "', '"
                . php2MySqlTime(js2PhpTime($st)) . "', '"
                . php2MySqlTime(js2PhpTime($et)) . "', '"
                . mysql_real_escape_string($ade) . "' )";
        //echo($sql);
        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
            $ret['Data'] = mysql_insert_id();
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function addDetailedCalendar($st, $et, $sub, $ade, $etid, $vid, $comctrl,$clkctrl, $fstv, $dtlurl, $dscr, $color, $tz) {

    $ret = array();

    $gUid = new CalendarUser();
    $login_id = $gUid->getCurrentUserID();

    try {
        $db = new DBConnection();
        $db->getConnection();

        if(checkExistEvent($sub, $etid, $vid, $st, $et, $ade))
        {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "已經存在相同的Event(事件）";
            return $ret;
        }
        if(checkIsOutXnumberDays($st,$et))
        {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "超出日期控制範圍";
            return $ret;
        }

        $pic_path = uploadADImage(); //jace 2011826
        if (!$pic_path['IsSuccess']) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = $pic_path['Msg'];
            return $ret;
        }
        $flash_path = uploadADFlash(); //jace  201194

        $sql = "insert into `event` (`subject`, `start_time`, `end_time`, `is_allday_event`,
        `etid`,`vid`,`commercial_control`,`click_window_control`,`festival`,`detail_url`, `description`,`picture_paths`,`flash_paths`,`uid`,`color`) values ('"
                . mysql_real_escape_string($sub) . "', '"
                . php2MySqlTime(js2PhpTime($st)) . "', '"
                . php2MySqlTime(js2PhpTime($et)) . "', '"
                . mysql_real_escape_string($ade) . "', '"
                . $etid . "', '"
                . $vid . "', '"
                . mysql_real_escape_string($comctrl). "', '"
                . mysql_real_escape_string($clkctrl). "', '"
                . mysql_real_escape_string($fstv) . "', '"
                . mysql_real_escape_string($dtlurl) . "', '"
                . mysql_real_escape_string($dscr) . "', '"
                . mysql_real_escape_string($pic_path['FilePaths']) . "', '"
                . mysql_real_escape_string($flash_path['FilePaths']) . "', '"
                . $login_id . "', '"
                . mysql_real_escape_string($color) . "' )";
        //echo($sql);
        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
            $ret['Data'] = mysql_insert_id();
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function addDetailedCalendarAndUpdateVenue($st, $et, $sub, $ade, $etid, $vid, $fstv,$comctrl, $dscr, $color, $tz, $v_telephones, $v_addresses, $v_urls, $v_contact) {
    $ret = array();

    $gUid = new CalendarUser();
    $login_id = $gUid->getCurrentUserID();

    try {
        $db = new DBConnection();
        $db->getConnection();
        if(checkExistEvent($sub, $etid, $vid, $st, $et, $ade))
        {
             $ret['IsSuccess'] = false;
            $ret['Msg'] = "已經存在相同的Event(事件）";
            return $ret;
        }
        
        if(checkIsOutXnumberDays($st,$et))
        {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "超出日期控制範圍";
            return $ret;
        }
        
        $pic_path = uploadADImage(); //jace 2011826
        if (!$pic_path['IsSuccess']) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = $pic_path['Msg'];
            return $ret;
        }
        $flash_path = uploadADFlash(); //jace  201194

        $sql = "INSERT INTO `event` (`subject`, `start_time`, `end_time`, `is_allday_event`,
        `etid`,`vid`,`festival`,`detail_url`, `description`,`picture_paths`,`flash_paths`,`uid`,`color`) VALUES ('"
                . mysql_real_escape_string($sub) . "', '"
                . php2MySqlTime(js2PhpTime($st)) . "', '"
                . php2MySqlTime(js2PhpTime($et)) . "', '"
                . mysql_real_escape_string($ade) . "', '"
                . $etid . "', '"
                . $vid . "', '"
                . mysql_real_escape_string($fstv) . "', '"
                . mysql_real_escape_string($loc) . "', '"
                . mysql_real_escape_string($dscr) . "', '"
                . mysql_real_escape_string($pic_path['FilePaths']) . "', '"
                . mysql_real_escape_string($flash_path['FilePaths']) . "', '"
                . $login_id . "', '"
                . mysql_real_escape_string($color) . "' ); ";

        $sql.= "UPDATE `venue` SET address_zh_hk = "
                . mysql_real_escape_string($v_addresses) . "', '"
                . "telephones = "
                . mysql_real_escape_string($v_telephones) . "', '"
                . "urls = "
                . mysql_real_escape_string($v_urls) . "', '"
                . "contact_person = "
                . mysql_real_escape_string($v_contact) . "', '"
                . "WHERE vid = "
                . $vid;

        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
            $ret['Data'] = mysql_insert_id();
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function listCalendarByRange($sd, $ed, $etid, $cid, $vid) {
    $ret = array();
    $ret['events'] = array();
    $ret["issort"] = true;
    $ret["start"] = php2JsTime($sd);
    $ret["end"] = php2JsTime($ed);
    $ret['error'] = null;

    try {
        $db = new DBConnection();
        $db->getConnection();
        $sql = "SELECT 
            `event`.`eid`, `event`.`subject`,`event`.`start_time`,`event`.`end_time`, 
            `event`.`is_allday_event`,`event`.`color`,`event`.`detail_url`,
            `event`.`description`,`event`.`picture_paths`,`event`.`flash_paths`,
            `event`.`vid`,`event`.`etid`,`event`.`uid`,`event`.`commercial_control`,`event`.`click_window_control`,`event`.`festival`,
            `venue`.`name_zh_hk` as `vname_zh_hk`,`event_type`.`name_zh_hk` as `etname_zh_hk`,
            `venue`.`address_zh_hk` as `vadrname_zh_hk`,`venue`.`urls` as `vurls`,`event_type`.`color_mark`,
            `city`.`name_zh_hk` as `cname_zh_hk`
            FROM `event` 
            INNER JOIN `venue` ON `event`.`vid` = `venue`.`vid` 
            INNER JOIN `city` ON `city`.`cid` = `venue`.`cid`
            INNER JOIN `event_type` ON `event`.`etid` = `event_type`.`etid`";
   
        $sql .= " WHERE `start_time` BETWEEN '" . php2MySqlTime($sd) . "' AND '" . php2MySqlTime($ed) . "'";
        
        $sql .=" AND `venue`.`delete_flag` = 0 AND `city`.`delete_flag` = 0 AND `event_type`.`delete_flag` = 0 ";

        if (!empty($etid)) {
            $sql .= " AND `event`.`etid` = " . $etid;
        }

        if (!empty($cid)) {
            $sql .= " AND `venue`.`cid` = " . $cid;
        }
        if (!empty($vid)) {
            $sql .= " AND `venue`.`vid` = " . $vid;
        }
        
        $sql.= " ORDER BY `start_time` ASC";
        $handle = mysql_query($sql);

        while ($row = mysql_fetch_object($handle)) {
 
            $ret['events'][] = array(
                $row->eid, //0
                $row->subject,
                php2JsTime(mySql2PhpTime($row->start_time)),
                php2JsTime(mySql2PhpTime($row->end_time)),
                $row->is_allday_event,
                0, //more than one day event
                //$row->InstanceType,
                0, //Recurring event,
                //$row->color,
                $row->color_mark, //7
                1, //editable

                '', //$attends
                $row->detail_url, //10
                $row->description,
                $row->picture_paths, //12
                $row->vid,
                $row->etid,
                $row->uid,
                $row->vname_zh_hk,
                $row->etname_zh_hk,
                $row->cname_zh_hk,
                $row->flash_paths,  //19
                $row->commercial_control, //20
                $row->festival, //21
                $row->vadrname_zh_hk,
                $row->vurls,
                $row->click_window_control //24
            );
        }
    } catch (Exception $e) {
        $ret['error'] = $e->getMessage();
    }
    return $ret;
}

function getAllEventTypes() {
    return getEventTypeByEventTypeId(NULL);
}

function getEventTypeByEventTypeId($etid) {
    $ret = array();
    $ret['types'] = array();
    $ret['error'] = null;

    $sql = "SELECT `etid`,`name_zh_hk` FROM `event_type` WHERE `delete_flag` = 0 ";
    if (!empty($etid)) {
        $sql .= " AND `etid` = " . $etid;
    }

    try {
        $db = new DBConnection();
        $db->getConnection();

        $handle = mysql_query($sql);
        while ($row = mysql_fetch_object($handle)) {
            $ret['types'][] = array(
                $row->etid,
                $row->name_zh_hk
            );
        }
    } catch (Exception $e) {
        $ret['error'] = $e->getMessage();
    }

    return $ret;
}

function getAllCities() {
    return getCityByCityId(NULL);
}

function getCityByCityId($cid) {
    $ret = array();
    $ret['cities'] = array();
    $ret['error'] = null;

    $sql = "SELECT `cid`,`name_zh_hk` FROM `city` WHERE `delete_flag` = 0 ";
    if (!empty($etid)) {
        $sql .= " AND `cid` = " . $cid;
    }

    try {
        $db = new DBConnection();
        $db->getConnection();

        $handle = mysql_query($sql);
        while ($row = mysql_fetch_object($handle)) {
            $ret['cities'][] = array(
                $row->cid,
                $row->name_zh_hk
            );
        }
    } catch (Exception $e) {
        $ret['error'] = $e->getMessage();
    }

    return $ret;
}

function getVenuesByCityId($cid) {
    $ret = array();
    $ret['venues'] = array();
    $ret['error'] = null;

    $sql = "SELECT `vid`, `name_zh_hk`,`cid` FROM `venue` WHERE `delete_flag` = 0 ";
    if (!empty($cid)) {
        $sql .= " AND `cid` = " . $cid;
    }

    try {
        $db = new DBConnection();
        $db->getConnection();

        $handle = mysql_query($sql);
        while ($row = mysql_fetch_object($handle)) {
            $ret['venues'][] = array(
                $row->vid,
                $row->name_zh_hk,
                //$row->telephones,
                //$row->urls,
                //$row->address_zh_hk,
                //$row->contact_person,
                $row->cid
            );
        }
    } catch (Exception $e) {
        $ret['error'] = $e->getMessage();
    }

    return $ret;
}

function getVenueByVenueId($vid) {
    $ret = array();
    $ret['venue'] = array();
    $ret['error'] = null;

    if (empty($vid)) {
        $ret['error'] = 'Please input Venue Id';
    } else {
        $sql = "SELECT * FROM `venue` WHERE `vid` = " . $vid;

        try {
            $db = new DBConnection();
            $db->getConnection();

            $handle = mysql_query($sql);
            while ($row = mysql_fetch_object($handle)) {
                $ret['venue'][] = array(
                    $row->vid,
                    $row->name_zh_hk,
                    $row->telephones,
                    $row->urls,
                    $row->address_zh_hk,
                    $row->contact_person,
                    $row->cid
                );
            }
        } catch (Exception $e) {
            $ret['error'] = $e->getMessage();
        }
    }
    return $ret;
}

function listCalendar($day, $type, $etid, $cid, $vid) {
    $phpTime = js2PhpTime($day);
    //echo $phpTime . "+" . $type;
    switch ($type) {
        case "month":
            $st = mktime(0, 0, 0, date("m", $phpTime), 1, date("Y", $phpTime));
            $et = mktime(0, 0, -1, date("m", $phpTime) + 1, 1, date("Y", $phpTime));
            break;
        case "week":
            //suppose first day of a week is monday 
            $monday = date("d", $phpTime) - date('N', $phpTime) + 1;
            //echo date('N', $phpTime);
            $st = mktime(0, 0, 0, date("m", $phpTime), $monday, date("Y", $phpTime));
            $et = mktime(0, 0, -1, date("m", $phpTime), $monday + 7, date("Y", $phpTime));
            break;
        case "day":
            $st = mktime(0, 0, 0, date("m", $phpTime), date("d", $phpTime), date("Y", $phpTime));
            $et = mktime(0, 0, -1, date("m", $phpTime), date("d", $phpTime) + 1, date("Y", $phpTime));
            break;
    }
    //echo $st . "--" . $et;
    return listCalendarByRange($st, $et, $etid, $cid, $vid);
}

function updateCalendar($id, $st, $et) {
    $ret = array();
    try {
        $db = new DBConnection();
        $db->getConnection();
        $sql = "update `event` set"
                . " `start_time`='" . php2MySqlTime(js2PhpTime($st)) . "', "
                . " `end_time`='" . php2MySqlTime(js2PhpTime($et)) . "' "
                . "where `eid`=" . $id;
        //echo $sql;
        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function updateDetailedCalendar($id, $st, $et, $sub, $ade, $fest, $dtlurl, $dscr, $etid, $vid, $comctrl,$clkctrl, $color, $tz) {
    $ret = array();

    $gUid = new CalendarUser();
    $login_id = $gUid->getCurrentUserID();

    try {
        $db = new DBConnection();
        $db->getConnection();

        if(checkExistEvent($sub, $etid, $vid, $st, $et, $ade,$id))
        {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "已經存在相同的Event(事件）";
            return $ret;
        }
        
        //jace 2011827 start
        $old_st=$_POST["iptvstarttime"];
        $old_et=$_POST["iptvendtime"];
        if($old_st!='' && $old_et!='')
        {
            if(checkIsOutXnumberDays($old_st,$old_et))//這兩個時間應該使用修改前的日期
            {
                $ret['IsSuccess'] = false;
                $ret['Msg'] = "超出日期控制範圍的不允許修改";
                return $ret;
            }
        }
        if(checkIsOutXnumberDays($st,$et))
        {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "超出日期控制範圍";
            return $ret;
        }
        
        $pic_path = uploadADImage();
        if (!$pic_path['IsSuccess']) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = $pic_path['Msg'];
            return $ret;
        }
        $flash_path = uploadADFlash(); //jace  201194

        $sql = "update `event` set"
                . " `start_time`='" . php2MySqlTime(js2PhpTime($st)) . "', "
                . " `end_time`='" . php2MySqlTime(js2PhpTime($et)) . "', "
                . " `subject`='" . mysql_real_escape_string($sub) . "', "
                . " `is_allday_event`='" . mysql_real_escape_string($ade) . "', "
                . " `festival`='" . mysql_real_escape_string($fest) . "', "
                . " `detail_url`='" . mysql_real_escape_string($dtlurl) . "', "
                . " `description`='" . mysql_real_escape_string($dscr) . "', "
                . " `etid`='" . mysql_real_escape_string($etid) . "', "
                . " `vid`='" . mysql_real_escape_string($vid) . "', "
                . " `commercial_control`='" . mysql_real_escape_string($comctrl) . "', "
                . " `click_window_control`='" . mysql_real_escape_string($clkctrl) . "' ";
        if ($pic_path['FilePaths'] != "") {
            $sql .= "," . " `picture_paths`='" . mysql_real_escape_string($pic_path['FilePaths']) . "' ";
        }
        if ($flash_path['FilePaths'] != "") {
            $sql .= "," . " `flash_paths`='" . mysql_real_escape_string($flash_path['FilePaths']) . "' ";
        }
        if ($color != NULL) {
            $sql .= "," . " `color`='" . mysql_real_escape_string($color) . "' ";
        }
        $sql .= "where `eid`=" . $id;


        //. " `color`='" . mysql_real_escape_string($color) . "' "
        //. "where `eid`=" . $id;
        //echo $sql;
        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function removeCalendar($id) {
    $ret = array();
    try {
        $db = new DBConnection();
        $db->getConnection();
        $sql = "delete from `event` where `eid`=" . $id;
        if (mysql_query($sql) == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = mysql_error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = '添加成功';
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}

function uploadADFlash() {
    $ret = array();
    $re = "";
    $cs_parameter = new cs_parameter();
    $strFileInputTypeNameFlash = "V_flash";
    $arrayFileTypes = preg_split('/;/', $cs_parameter->getFlashBrowerFileType()); //array("image/jpeg");
    $extName = $cs_parameter->getFlashExtName(); // 'jpg,jpeg';

    $intFileSize = $cs_parameter->getFlashFileSize(); //300000;

    $uploadPath = $cs_parameter->getFlashUploadPath();
    $stringUploadDir = $_SERVER["DOCUMENT_ROOT"]; //."/" ; //eg: d:/phpweb

    $uploadFile = new PHPUploadFile();

    $server_name = "";
    if ($_FILES [$strFileInputTypeNameFlash] ["tmp_name"] != '') {
        //校驗文件尺寸
//        $ret_size = checkImageSize($_FILES [$strFileInputTypeNameFlash] ["tmp_name"], 1);
//        if (!$ret_size["isPass"]) {
//            $ret['IsSuccess'] = false;
//            $ret['Msg'] = "Flash的尺寸不符合要求," . $ret_size["size"];
//            $ret['FilePaths'] = $re;
//            return $ret;
//        }
        //开始上传
        $upFileName = $uploadFile->uploadFile($strFileInputTypeNameFlash, $arrayFileTypes, $extName, $intFileSize, 2);
        //上传完成
        $re = str_replace($stringUploadDir, $server_name, $upFileName);

        if ($re != "") {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = "上傳成功";
            $ret['FilePaths'] = $re;
            return $ret;
        }
    }
    $ret['IsSuccess'] = true;
    $ret['Msg'] = "無文檔上傳";
    $ret['FilePaths'] = $re;
    return $ret;
}
function checkExistEvent($subject, $etid, $vid, $st, $et, $isallday, $eid="")
{
    $ev=new event();
    $exist=$ev->existEvent($subject, $etid, $vid, php2MySqlTime(js2PhpTime($st)) ,  php2MySqlTime(js2PhpTime($et)) , $isallday, $eid);
    if($exist==true)
        return true;
    else
        return false;
}
//jace 2011826 start
function uploadADImage() {
    $ret = array();
    $re = "";
    $cs_parameter = new cs_parameter();

    $strFileInputTypeNameSmall = "V_picture_small";
    $strFileInputTypeNameMiddle = "V_picture_middle";
    $strFileInputTypeNameBig = "V_picture_big";

    $arrayFileTypes = preg_split('/;/', $cs_parameter->getPictureBrowerFileType()); //array("image/jpeg");
    $extName = $cs_parameter->getPictureExtName(); // 'jpg,jpeg';

    $intFileSize = $cs_parameter->getPicAdFileSize(); //300000;

    $uploadPath = $cs_parameter->getimgUploadPath();
    $stringUploadDir = $_SERVER["DOCUMENT_ROOT"]; //."/" ; //eg: d:/phpweb

    $uploadFile = new PHPUploadFile();
    //$server_name = "http://".$_SERVER["SERVER_NAME"]."/";//或=""
    if (isset($_POST['iptvpicturepaths']) && $_POST['iptvpicturepaths'] != "") {
        $re = $_POST["iptvpicturepaths"];
        $chars = preg_split('/;/', $re);
        $re_small = $chars[0]; //在更新的情況下要先取得原值
        $re_middle = $chars[1]; //在更新的情況下要先取得原值
        $re_big = $chars[2]; //在更新的情況下要先取得原值
    } else {
        $re = "";
        $re_small = ""; //在更新的情況下要先取得原值
        $re_middle = "";
        $re_big = ""; //在更新的情況下要先取得原值
    }

    $server_name = "";
    if ($_FILES [$strFileInputTypeNameSmall] ["tmp_name"] != '') {
        //校驗文件尺寸
        $ret_size = checkImageSize($_FILES [$strFileInputTypeNameSmall] ["tmp_name"], 1);
        if (!$ret_size["isPass"]) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "小圖片的尺寸不符合要求," . $ret_size["size"];
            $ret['FilePaths'] = $re;
            return $ret;
        }
        //开始上传
        $upFileName = $uploadFile->uploadFile($strFileInputTypeNameSmall, $arrayFileTypes, $extName, $intFileSize, 1);
        //上传完成
        $re_small = str_replace($stringUploadDir, $server_name, $upFileName);
    }
    if ($_FILES [$strFileInputTypeNameMiddle] ["tmp_name"] != '') {
        //校驗文件尺寸
        $ret_size = checkImageSize($_FILES [$strFileInputTypeNameMiddle] ["tmp_name"], 2);
        if (!$ret_size["isPass"]) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "中圖片的尺寸不符合要求," . $ret_size["size"];
            $ret['FilePaths'] = $re;
            return $ret;
        }
        //开始上传
        $upFileName = $uploadFile->uploadFile($strFileInputTypeNameMiddle, $arrayFileTypes, $extName, $intFileSize, 1);
        //上传完成
        $re_middle = str_replace($stringUploadDir, $server_name, $upFileName);
    }
    if ($_FILES [$strFileInputTypeNameBig] ["tmp_name"] != '') {
        //校驗文件尺寸
        $ret_size = checkImageSize($_FILES [$strFileInputTypeNameBig] ["tmp_name"], 3);
        if (!$ret_size["isPass"]) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = "大圖片的尺寸不符合要求," . $ret_size["size"];
            $ret['FilePaths'] = $re;
            return $ret;
        }
        //开始上传
        $upFileName = $uploadFile->uploadFile($strFileInputTypeNameBig, $arrayFileTypes, $extName, $intFileSize, 1);
        //上传完成
        $re_big = str_replace($stringUploadDir, $server_name, $upFileName);
    }
    if ($re_small != "" || $re_big != "") {
        $re = $re_small . ";" . $re_middle . ";" . $re_big;

        $ret['IsSuccess'] = true;
        $ret['Msg'] = "上傳成功";
        $ret['FilePaths'] = $re;
        return $ret;
    }

    $ret['IsSuccess'] = true;
    $ret['Msg'] = "無文檔上傳";
    $ret['FilePaths'] = $re;
    return $ret;
}

function checkIsOutXnumberDays($start_time, $end_time) {
    $cs_parameter = new cs_parameter();
    $x = $cs_parameter->getXNumberDays();

    $pre_x_date = mktime(0, 0, 0, date("m"), date("d") - $x, date("Y"));
    $last_x_date = mktime(0, 0, 0, date("m"), date("d") + $x, date("Y"));
    
    if (date("Y-m-d", strtotime($start_time)) < date("Y-m-d", $pre_x_date)
            || date("Y-m-d", strtotime($start_time)) > date("Y-m-d", $last_x_date)
            || date("Y-m-d", strtotime($end_time)) > date("Y-m-d", $last_x_date)
            || date("Y-m-d", strtotime($end_time)) < date("Y-m-d", $pre_x_date)
            ) {
        return true;
    } else {
        return false;
        }
}

function checkImageSize($imgFile, $adPictureType) {
    //檢查圖片文件的分辨率
    //$adPictureType   1:small  2:middle    3:big
    $ret = array();
    $size = getimagesize($imgFile);
    $width = $size[0];
    $height = $size[1];
    $cfg_width = 0;
    $cfg_height = 0;
    $cs_parameter = new cs_parameter();
    switch ($adPictureType) {
        case 1:
            $cfg_width = $cs_parameter->getPicSmallWidth();
            $cfg_height = $cs_parameter->getPicSmallHeight();
            break;
        case 2:
            $cfg_width = $cs_parameter->getPicMiddleWidth();
            $cfg_height = $cs_parameter->getPicMiddleHeight();
            break;
        case 3:
            $cfg_width = $cs_parameter->getPicBigWidth();
            $cfg_height = $cs_parameter->getPicBigHeight();
            break;
        default:
            break;
    }
    //if ($width != $cfg_width || $height != $cfg_height) { //filter the more size than parameter cfg
    if ($width > $cfg_width || $height > $cfg_height) {
        $ret["isPass"] = false;
    } else {
        $ret["isPass"] = true;
    }
    $ret["size"] = $width . "x" . $height . " [WxH: " . $cfg_width . "x" . $cfg_height . "]";
    return $ret;
}

//jace 2011826 end

header('Content-type:text/html;charset=UTF-8');
$method = $_GET["method"];
switch ($method) {
    case "add":
        $ret = addCalendar($_POST["CalendarStartTime"], $_POST["CalendarEndTime"], $_POST["CalendarTitle"], $_POST["IsAllDayEvent"]);
        break;

    case "list": //OK
        $etid = ($_POST["eventtypeid"] == (string) 0) ? NULL : $_POST["eventtypeid"];
        $cid = ($_POST["cityid"] == (string) 0) ? NULL : $_POST["cityid"];
        $vid = ($_POST["venueid"] == (string) 0) ? NULL : $_POST["venueid"];
        $ret = listCalendar($_POST["showdate"], $_POST["viewtype"], $etid, $cid, $vid);
        break;
    case "update":
        $ret = updateCalendar($_POST["calendarId"], $_POST["CalendarStartTime"], $_POST["CalendarEndTime"]);
        break;
    case "remove": //OK
        $ret = removeCalendar($_POST["calendarId"]);
        break;
    case "adddetails":
        $st = $_POST["stpartdate"] . " " . $_POST["stparttime"];
        $et = $_POST["etpartdate"] . " " . $_POST["etparttime"];
        if (isset($_GET["id"])) {
            $ret = updateDetailedCalendar($_GET["id"], $st, $et, $_POST["Subject"], isset($_POST["IsAllDayEvent"]) ? 1 : 0, $_POST["Festival"], $_POST["DetailUrl"], $_POST["Description"], $_POST["Type"], $_POST["Venue"],$_POST["CommercialControl"],$_POST["ClickWindowControl"], isset($_POST["ColorValue"]) ? $_POST["ColorValue"] : NULL, $_POST["timezone"]);
        } else {
            if (isset($_POST["IsVenueChanged"]) && !empty($_POST["IsVenueChanged"])) {
                $ret = addDetailedCalendarAndUpdateVenue($st, $et, $_POST["Subject"], isset($_POST["IsAllDayEvent"]) ? 1 : 0, $_POST["Type"], $_POST["Venue"], $_POST["Festival"], $_POST["Description"], $_POST["ColorValue"], $_POST["timezone"], $_POST["V_address"], $_POST["V_telephones"], $_POST["V_urls"], $_POST["V_contact"]);
            } else {
                $ret = addDetailedCalendar($st, $et, //OK                  
                        $_POST["Subject"], isset($_POST["IsAllDayEvent"]) ? 1 : 0, $_POST["Type"], $_POST["Venue"],$_POST["CommercialControl"],$_POST["ClickWindowControl"], $_POST["Festival"], $_POST["DetailUrl"], $_POST["Description"], $_POST["ColorValue"], $_POST["timezone"]);
            }
        }
        break;

    case "getVenuesByCityId": //OK
        $ret = getVenuesByCityId(isset($_POST["cityid"]) ? $_POST["cityid"] : NULL);
        break;
    case "getVenueByVenueId": //OK
        $ret = getVenueByVenueId(isset($_POST["venueid"]) ? $_POST["venueid"] : NULL);
        break;
    case "getAllEventTypes": //OK
        $ret = getAllEventTypes();
        break;
    case "getAllCities": //OK
        $ret = getAllCities();
        break;
}
echo json_encode($ret);
?>